import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:test01/config/config.dart';
import 'package:test01/model/user_model.dart';

class LoginScreen extends StatefulWidget {
  const LoginScreen({Key? key}) : super(key: key);

  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  bool allowShow = false;
  String _username = "";
  String _password = "";
  UserModelItem _user = new UserModelItem();
  bool _allowLogin = false;
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _prefs.then((value) {
      if(value.getInt("userId")!=null) {
        Navigator.pushNamed(context, "/");
      } else {
        setState(() {
          allowShow = true;

        });
      }
    });

  }
  _changeAllowLogin() {
    if (_username!="" && _username != null && _password!="" && _password!= null) {
      setState(() {
        _allowLogin = true;
      });
    }
  }
  _login() async {
    var api = "${Config.domain}user/userLogin?username=$_username&&password=$_password";
    var result = await Dio().get(api);
    var userModel = UserModel.fromJson(result.data!);
    if (userModel.status == 200) {
      _user = userModel.data!;
    }
    return userModel;
  }

  @override
  Widget build(BuildContext context) {
    if (allowShow) {return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        elevation: 0,
        centerTitle: true,
        backgroundColor: Colors.white,
        title:
        Text("登录", style: TextStyle(fontSize: 30.w, color: Colors.black87)),
      ),
      body: Container(
        color: Colors.white,
        height: double.infinity,
        child: ListView(
          children: [
            Container(
              margin: EdgeInsets.only(left: 30.w, top: 80.h),
              height: 100.h,
              child: Text(
                "使用用户名和密码登录",
                style: TextStyle(fontSize: 45.w, color: Colors.black87),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: 52.h),
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(bottom: BorderSide(width: 2.h, color: Colors.black26))
              ),
              child: Row(children: [
                Container(
                  margin: EdgeInsets.only(left: 20.w),
                  color: Colors.white,
                  height: 56.h,
                  width: 100.w,
                  child: Text("用户名", style: TextStyle(fontSize: 30.w, color: Colors.black87)),
                ),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: 30.w),
                    child: TextField(
                      onChanged: (value) {
                        _username = value;
                        _changeAllowLogin();
                      },
                      cursorColor: Colors.black,
                      cursorHeight: 56.h,
                      decoration: InputDecoration(
                          hintText: "请输入用户名",
                          hintStyle: TextStyle(fontSize: 30.w, color: Colors.black26),
                          border: InputBorder.none),
                    ),
                  ),
                )
              ]),
            ),
            Container(
              decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border(bottom: BorderSide(width: 2.h, color: Colors.black26))
              ),
              child: Row(children: [
                Container(
                  margin: EdgeInsets.only(left: 20.w),
                  color: Colors.white,
                  height: 56.h,
                  width: 100.w,
                  child: Text("密码", style: TextStyle(fontSize: 30.w, color: Colors.black87)),
                ),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: 30.w),
                    child: TextField(
                      onChanged: (value) {
                        _password = value;
                        if (value.length >=  6) {
                          _changeAllowLogin();
                        }
                        if (value.length < 6) {
                          setState(() {
                            _allowLogin = false;
                          });
                        }
                      },
                      obscureText: true,
                      cursorColor: Colors.black,
                      cursorHeight: 56.h,
                      decoration: InputDecoration(
                          hintText: "请输入密码",
                          hintStyle: TextStyle(fontSize: 30.w, color: Colors.black26),
                          border: InputBorder.none),
                    ),
                  ),
                )
              ]),
            ),
            Container(
              margin: EdgeInsets.only(top: 35.h, right: 35.w),
              alignment: Alignment.centerRight,
              child: const Text("没有账号？ 点击进行注册"),
            ),
            Container(
              padding: EdgeInsets.only(top: 35.h),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  ElevatedButton(
                    onPressed: _allowLogin == false ? null : () {
                      Future<dynamic> req = _login();
                      req.then((value) {
                        if (value.status == 200) {
                          _prefs.then((value) {
                            value.setInt("userId", _user.userId!);
                            Navigator.pushNamed(context, "/");
                          });
                        }
                        else {
                          showDialog(
                            context: context,
                            builder: (context) {
                              return AlertDialog(
                                title: Container(
                                    alignment: Alignment.center,
                                    child: Text(value.msg!,
                                      style: TextStyle(fontSize: 30.w),)
                                ),
                                actions: [
                                  Container(
                                    alignment: Alignment.center,
                                    child: OutlinedButton(onPressed: () {
                                      Navigator.pop(context);
                                    }, child: const Text("确定", style: TextStyle(
                                        color: Colors.lightGreen
                                    ),)),
                                  )
                                ],
                              );
                            },
                          );
                        }
                      });
                    },
                    child: Container(
                      alignment: Alignment.center,
                      child: const Text("登录"),
                      width: 200.w,
                    ),
                    style: ElevatedButton.styleFrom(primary: Colors.lightGreen),
                  ),
                  ElevatedButton(
                    onPressed: () {
                      Navigator.pushNamed(context, "/register");
                    },
                    child: Container(
                      alignment: Alignment.center,
                      child: const Text("注册"),
                      width: 200.w,
                    ),
                    style: ElevatedButton.styleFrom(primary: Colors.lightGreen),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );}
    else {
      return Text("");
    }
  }
}
